// 统一分析相关的类型定义

export type SeverityLevel = 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
export type AnalysisSource = 'RULE' | 'LLM';
export type ProblemCategory = 'SYNTAX' | 'FUNCTION' | 'DATATYPE' | 'PERFORMANCE' | 'COMPATIBILITY';

/**
 * 统一分析请求
 */
export interface UnifiedAnalysisRequest {
  sqlContent: string;
  sourceDbType: string;
  targetDbType: string;
  aiEnhancementEnabled?: boolean;
  taskName?: string;
  userId?: number;
  analysisOptions?: Record<string, any>;
}

/**
 * SQL语句信息 - 支持语句编号
 */
export interface SqlStatement {
  statementNumber: number;        // 新增：SQL语句编号
  content: string;
  sourceType: string;
  sqlType: string;
  lineNumber: number;
  columnNumber?: number;
  lineStart?: number;             // 新增：在原文中的起始行号
  lineEnd?: number;               // 新增：在原文中的结束行号
  className?: string;
  methodName?: string;
  isNativeQuery?: boolean;
  isDerivedQuery?: boolean;
}

/**
 * 兼容性问题 - 统一格式，支持SQL语句编号和AI验证
 */
export interface CompatibilityIssue {
  id: string;
  statementNumber: number;        // 新增：所属SQL语句编号
  ruleId?: string;                // 规则分析时有值，AI分析时为AI001等
  ruleName: string;
  issueType: string;
  severity: SeverityLevel;
  category: ProblemCategory;      // 问题分类
  description: string;
  suggestion: string;
  sqlContent: string;             // 完整SQL语句内容
  sqlFragment?: string;           // 新增：具体问题片段
  fileName?: string;
  lineNumber: number;             // 精确行号
  columnNumber: number;           // 精确列号
  startOffset?: number;           // 字符偏移量
  endOffset?: number;
  analysisSource: AnalysisSource; // 问题来源：RULE 或 LLM
  confidence?: number;            // LLM分析时的置信度
  originalCode?: string;          // 原始问题代码
  suggestedCode?: string;         // 建议替换代码
  gitFileUrl?: string;
  
  // AI增强验证字段 (v4.2新增)
  ruleAnalysisConfirmed?: boolean;      // 规则分析是否被AI确认（已弃用，现通过aiOptimized和aiConfidenceScore判断）
  aiIssueDescription?: string;          // AI分析的问题描述（可能与规则描述不同）
  aiConfidenceScore?: number;           // AI分析置信度(0.00-1.00)，>=0.7为确认，<0.7为质疑
  optimizedSql?: string;                // AI优化后的完整SQL语句
  optimizationExplanation?: string;     // AI优化说明
  analysisEngine?: string;              // 分析引擎：RULE/AI_ENHANCED
  aiOptimized?: boolean;                // 是否经过AI优化（用于判断是否AI验证过）
  aiVerificationDetails?: Record<string, any>; // AI验证详情
}

/**
 * 优化建议
 */
export interface OptimizationSuggestion {
  id: string;
  type: 'FUNCTION_REPLACE' | 'SYNTAX_ADJUST' | 'PERFORMANCE_TUNE' | 'TYPE_CONVERT';
  originalCode: string;
  optimizedCode: string;
  description: string;
  reason: string;
  ruleReference?: string;
  impact: SeverityLevel;
  lineNumber: number;
  columnNumber: number;
  confidence?: number;
}

/**
 * 分析统计
 */
export interface AnalysisStatistics {
  totalStatements: number;
  totalIssues: number;
  highSeverityCount: number;
  mediumSeverityCount: number;
  lowSeverityCount: number;
  infoCount: number;
  categoryCounts: Record<ProblemCategory, number>;
  analysisTime: string;
  processingTimeMs: number;
}

/**
 * 统一分析结果
 */
export interface UnifiedAnalysisResult {
  success: boolean;
  errorMessage?: string;
  sqlStatements: SqlStatement[];
  issues: CompatibilityIssue[];
  optimizations?: OptimizationSuggestion[];
  statistics: AnalysisStatistics;
  optimizedSql?: string;              // AI增强模式下的优化SQL
  optimizationExplanation?: string;   // 优化说明
  metadata?: {
    modelName?: string;
    processingTime?: number;
    tokensUsed?: number;
    confidence?: number;
  };
}

/**
 * SQL编辑器标记
 */
export interface EditorMarker {
  id: string;
  startLineNumber: number;
  startColumn: number;
  endLineNumber: number;
  endColumn: number;
  message: string;
  severity: 'error' | 'warning' | 'info' | 'hint';
  className?: string;
  source?: 'rule' | 'llm';
  issueId?: string;
}

/**
 * 数据库类型信息
 */
export interface DatabaseType {
  value: string;
  label: string;
  version?: string;
  icon?: React.ReactNode;
  description?: string;
}

/**
 * SQL示例
 */
export interface SqlExample {
  id: string;
  name: string;
  description: string;
  category: string;
  difficulty: 'BASIC' | 'INTERMEDIATE' | 'ADVANCED';
  sourceDbType: string;
  content: string;
  expectedIssues?: number;
}

/**
 * 分析配置
 */
export interface AnalysisConfig {
  enableRealTimeAnalysis: boolean;
  enableAutoOptimization: boolean;
  debounceDelay: number;
  maxResults: number;
  showLineNumbers: boolean;
  highlightIssues: boolean;
}

/**
 * AI分析语句级结果
 */
export interface AIStatementAnalysis {
  statementNumber: number;
  originalStatement: string;
  optimizedStatement?: string;     // 完整的优化后SQL语句（仅当有问题时提供）
  issues: AIIssueDetail[];
}

/**
 * AI问题详情
 */
export interface AIIssueDetail {
  ruleId?: string;                 // 关联的规则编号（如RULE001，如果AI识别出对应规则）
  ruleName: string;                // 规则名称或AI生成的问题类型名称
  severity: SeverityLevel;
  category: ProblemCategory;
  description: string;
  suggestion: string;              // 针对问题片段的修改建议
  problemFragment: string;         // 问题代码片段
  suggestedFragment: string;       // 建议替换片段（而非完整SQL）
  confidence: number;              // 置信度 0-100
}

/**
 * AI分析返回结构
 */
export interface AIAnalysisResponse {
  success: boolean;
  errorMessage?: string;
  statementAnalysis: AIStatementAnalysis[];
  metadata?: {
    modelName?: string;
    processingTime?: number;
    tokensUsed?: number;
  };
}

/**
 * 统一问题表格数据
 */
export interface UnifiedProblemData extends CompatibilityIssue {
  groupKey?: string;
  groupTitle?: string;
  groupColor?: string;
  optimizedSqlStatement?: string; // 完整的优化后SQL语句（语句级）
}

/**
 * 差异对比数据
 */
export interface DiffComparisonData {
  title: string;
  original: string;
  suggested: string;
  description: string;
  statementNumber: number;
}